import { usePermissionStore } from "@/store/modules/permission";
import { Directive, DirectiveBinding } from "vue";

/**
 * 按钮权限
 */
export const hasPerm: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    let btnPermission = usePermissionStore().pinia_curMenuInfo.buttonList || [];

    if (btnPermission && btnPermission.length > 0) {
      if (
        !btnPermission.filter((v) => {
          return v.permissionCode === value;
        }).length
      ) {
        if (el.parentNode) {
          el.parentNode.removeChild(el);
        } else el.remove();
      }
    } else {
      if (el.parentNode) {
        el.parentNode.removeChild(el);
      } else el.remove();
    }
  },
};

/**
 * 角色权限
 */
export const hasRole: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
  },
};

// 防抖
export const debounce: Directive = {
  mounted(el: HTMLElement, bind: DirectiveBinding) {
    if (typeof bind.value !== "function") return;
    bind.value.id = null;
    el.addEventListener("input", () => {
      clearTimeout(bind.value.id);
      bind.value.id = setTimeout(() => {
        bind.value();
      }, bind.arg || 1000);
    });
  },
};

// 节流  只对element组件的click事件生效，未使用组件库的可以使用  import { refDebounced } from '@vueuse/core' 中的方法
export const throttle: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    el.addEventListener("click", () => {
      if (!el.disabled) {
        el.disabled = true;
        setTimeout(() => {
          el.disabled = false;
        }, binding.value || 2000); //2000ms间隔时间
      }
    });
  },
};
